;; from https://daryl.wakatara.com/emacs-gtd-flow-evolved/#org-super-agenda
;; https://gist.github.com/wakatara/8f04061f74c852ff6887284a6a6e9bf2

;; Install straight.el
(defvar bootstrap-version)
(let ((bootstrap-file
       (expand-file-name "straight/repos/straight.el/bootstrap.el" user-emacs-directory))
      (bootstrap-version 5))
  (unless (file-exists-p bootstrap-file)
    (with-current-buffer
        (url-retrieve-synchronously
         "https://raw.githubusercontent.com/raxod502/straight.el/develop/install.el"
         'silent 'inhibit-cookies)
      (goto-char (point-max))
      (eval-print-last-sexp)))
  (load bootstrap-file nil 'nomessage))

(setq-default tab-width 2
      indent-tabs-mode  t
      tab-always-indent t)

;; Keybinds
(global-set-key [(hyper a)] 'mark-whole-buffer)
(global-set-key [(hyper v)] 'yank)
(global-set-key [(hyper c)] 'kill-ring-save)
(global-set-key [(hyper s)] 'save-buffer)
(global-set-key [(hyper l)] 'goto-line)
(global-set-key [(hyper w)]
                (lambda () (interactive) (delete-window)))
(global-set-key [(hyper z)] 'undo)

;; mac switch meta key
(defun mac-switch-meta nil 
  "switch meta between Option and Command"
  (interactive)
  (if (eq mac-option-modifier nil)
      (progn
	(setq mac-option-modifier 'meta)
	(setq mac-command-modifier 'hyper)
	)
    (progn 
      (setq mac-option-modifier nil)
      (setq mac-command-modifier 'meta)
      )
    )
  )

; Silence compiler warnings if using native compilation
; (setq native-comp-async-report-warnings-errors nil)

(setq delete-by-moving-to-trash t)
;; Set up the visible bell
(setq visible-bell t)
;; Revert Dired and other buffers
(setq global-auto-revert-non-file-buffers t)
;; Revert buffers when the underlying file has changed
(global-auto-revert-mode 1)

;; Make sure it is all utf-8
(prefer-coding-system 'utf-8)
(set-default-coding-systems 'utf-8)
(set-terminal-coding-system 'utf-8)
(set-keyboard-coding-system 'utf-8)
(setq default-buffer-file-coding-system 'utf-8)

(global-set-key (kbd "C-d") 'xeft)
(global-set-key (kbd "C-l") 'org-roam-dailies-goto-today)
(global-set-key (kbd "M-j") 'org-journal-new-entry)
(global-set-key (kbd "C-c C") 'comment-or-uncomment-region)
(global-set-key (kbd "C-c N") 'delete-file-and-buffer)  ; for "nuke"
(global-set-key (kbd "C-\`") 'neotree-toggle)
(global-set-key (kbd "C-1") 'delete-other-windows)
(global-set-key (kbd "C-3") 'split-window-right)
(global-set-key (kbd "M-s") 'save-buffer)
(global-set-key (kbd "M-c") 'copy-region-as-kill)
(global-set-key (kbd "M-v") 'pbpaste)
(global-set-key (kbd "M-z") 'undo-tree-undo)
(global-set-key (kbd "M-S-z") 'undo-tree-redo)


(straight-use-package 'use-package)

(straight-use-package
    '(nano-emacs :type git :host github :repo "rougier/nano-emacs"))

(setq nano-font-family-monospaced "IBM Plex Mono")
(setq nano-font-family-proportional "SF Pro Text")

(setq nano-font-size 14)
;; (load-theme 'nano-dark t)

(require 'nano-layout)
(defun nano-theme-set-spaceduck ()
  (setq frame-background-mode 'dark)
  (setq nano-color-foreground "#ecf0c1")
  (setq nano-color-background "#0f111b")
  (setq nano-color-highlight  "#1b1c36")
  (setq nano-color-critical   "#e33400")
  (setq nano-color-salient    "#00a4cc")
  (setq nano-color-strong     "#e39400")
  (setq nano-color-popout     "#f2ce00")
  (setq nano-color-subtle     "#7a5ccc")
  (setq nano-color-faded      "#b3a1e6"))
(nano-theme-set-spaceduck)
;;(require 'nano-theme-dark)

(require 'nano-base-colors)
(require 'nano-faces)
(nano-faces)
(require 'nano-theme)
(nano-theme)
(require 'nano-help)
(require 'nano-modeline)
(require 'nano-defaults)
(require 'nano-colors)
(require 'nano-writer)

;; Corrects PATH issues on osx
(when (memq window-system '(mac ns))
  (use-package exec-path-from-shell
    :straight t
    :config
    (exec-path-from-shell-initialize)))

;; ========== Org mode ==========

(use-package org
  :straight (:type built-in)
  :ensure org-contrib
  :defer t
  :bind ("C-c d" . org-decrypt-entry)
  :hook
  (org-mode . flyspell-mode)
  (before-save . zp/org-set-last-modified)
  :config
  (require 'org-crypt)
  (org-crypt-use-before-save-magic)
  (setq org-tags-exclude-from-inheritance (quote ("crypt")))
  (setq org-crypt-key "**Put your crypt key in here**")
  (setq auto-save-default nil)
  (setq variable-pitch-mode 1)
  (setq auto-fill-mode 0)
  (setq visual-line-mode 1)
  (setq
      org-startup-indented t
      org-enforce-todo-dependencies nil
      org-pretty-entities t
      org-use-sub-superscripts "{}"
      org-hide-emphasis-markers t
      org-hide-leading-stars t
      ;; show actual italicized text instead of /italicized text/
      ; org-odd-levels-only t
      org-agenda-block-separator ""
      org-fontify-whole-heading-line t
      org-fontify-done-headline t
      org-fontify-quote-and-verse-blocks t
      org-startup-with-inline-images t
      org-image-actual-width '(600)
      org-return-follows-link t
      org-ellipsis "  ▼"
      )
  :init
  (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
  (add-to-list 'auto-mode-alist '("\\.org_archive$" . org-mode))

  ;; General org-mode agenda eneration speedups
  (setq org-agenda-dim-blocked-tasks nil)

  (define-key global-map "\C-cl" 'org-store-link)
  (define-key global-map "\C-t" 'org-agenda)
  (define-key global-map "\C-cc" 'org-capture)

  (setq org-agenda-files (directory-files-recursively "~/Documents/org/" "\\.org$"))

  (setq org-agenda-skip-deadline-if-done t)
  ;; (setq org-agenda-skip-scheduled-if-done t)
  (setq org-deadline-warning-days 5)
  (setq org-agenda-skip-deadline-prewarning-if-scheduled 0)

  (setq org-agenda-todo-ignore-scheduled 'all)
  (setq org-agenda-todo-ignore-deadlines 'all)
  (setq org-agenda-todo-ignore-with-date 'all)
  (setq org-agenda-tags-todo-honor-ignore-options t)

  (setq org-todo-keywords '((type "TODO(t@/!)" "WIP (w@/!)" "FUP (@/!)" "GAVE(g@/!)" "|" "DONE(d@/!)" "KILL(k@/!)")))
  (setq org-log-into-drawer t)
  (setq org-log-done t)
  (setq org-log-reschedule t)
  (setq org-log-redeadline t)
  (setq org-enable-priority-commands nil)

  (setq org-agenda-deadline-leaders '("DUE:       " "In %3d d.: " "%2d d. ago: "))
  (setq org-agenda-scheduled-leaders '("DO:        " "Sched.%2dx: "))

  ;; prevent demoting heading also shifting text inside sections
  (setq org-adapt-indentation nil)

  ; ;; Org-gcal one way sync from gmail cal into emacs
  ; (use-package org-gcal
  ; :straight t
  ; :config
  ; (setq org-gcal-client-id " NEED TO PUT IN YOUR OWN ID HERE "
  ;  org-gcal-client-secret " NEED TO PUT IN YOUR OWN ID HERE "
  ;  org-gcal-file-alist '( (" you @ home mail.com" . "~/Documents/org/logs/calme.org")
                         ;; (" you at work .com " . "~/Documents/org/dailies/calwork.org")
  ;                        )))
  ;; (add-hook 'org-agenda-mode-hook (lambda () (org-gcal-fetch) ))
  ; (add-hook 'org-capture-after-finalize-hook (lambda () (org-gcal-sync) ))
  ; (setq plstore-cache-passphrase-for-symmetric-encryption t)
  
  ; Org Capture Inbox and refiling to Deft files
  (setq org-directory (expand-file-name "~/Documents/org/"))
  (setq org-default-notes-file (concat org-directory "/inbox.org"))
  (setq org-outline-path-complete-in-steps nil)         ; Refile in a single go
  (setq org-refile-use-outline-path 'file)              ; Show full paths for refiling
  (setq org-refile-targets
      '((nil :maxlevel . 3)
        (org-agenda-files :maxlevel . 3)))

) ; End of org-mode use-package block

(use-package writeroom-mode
	:straight t
	:commands (writeroom-mode))

; Used to replace graphics generation of latex code
(use-package math-preview
	:straight t
	:custom
    (math-preview-command "/opt/homebrew/bin/math-preview")
    (math-preview-scale 1.5)
    (math-preview-tex-marks-inline
			'(("$~" "~$")))
    (math-preview-tex-marks
	 '(("\\begin{equation}" "\\end{equation}")
		 ("\\begin{equation*}" "\\end{equation*}")
		 ("$$" "$$")
		 ))
  )
(add-hook 'org-mode-hook #'math-preview-all)

; Used to get enter-ext display of latex
(use-package org-fragtog
     :straight t)
(add-hook 'org-mode-hook 'org-fragtog-mode)
(defalias #'org-latex-preview #'math-preview-at-point)
(defalias #'org-clear-latex-preview #'math-preview-clear-region)

;; ========== All-the-icons to make emacs look nicer ==========

(straight-use-package 'all-the-icons)

;; ========== Text mode config ===========
; wrap at 80
(add-hook 'text-mode-hook '(lambda() (turn-on-auto-fill) (set-fill-column 80)))
(setq ispell-extra-args '("--lang=en_CA"))

(use-package markdown-mode
  :straight t
  :defer t
  (markdown-mode . flyspell-mode)
  :hook
  :mode
  (("\\.md\\'" . gfm-mode)
  ("\\.markdown\\'" . gfm-mode))
  :init
  (setq markdown-command "multimarkdown")
  ;; (setq markdown-header-scaling t)
  (setq markdown-fontify-code-blocks-natively t)
  (setq org-src-fontify-natively t)
  )

;; ========== calca mode ==============
(straight-use-package 'literate-calc-mode)

;; ========== Ledger mode =========
(use-package ledger-mode
	:straight t
	:defer t
	:hook
	(ledger-mode . outline-minor-mode)
	:bind
	(:map ledger-mode-map
				("TAB" . outline-toggle-children))
	:config
	(font-lock-add-keywords 'ledger-mode outline-font-lock-keywords))

;; ========== Undo tree ==========
(use-package undo-tree
  :straight t
  :defer t
  :init
  (global-undo-tree-mode)
  (setq undo-tree-visualizer-diff t)
  (setq undo-tree-visualizer-timestamps t)
  (setq undo-tree-history-directory-alist '(("." . "~/.emacs_undos")))
  )

;; ========== Neotree ==========
 (use-package neotree
   :straight t
   :defer t
   :init
   (setq neo-theme (if (display-graphic-p) 'icons 'arrow))
   (setq neo-theme 'arrow)
   )

;; ========== Git-gutter ==========
;; (use-package git-gutter
;;   :ensure t
;;   :defer t
;;   :init
;;   (global-git-gutter-mode t))

;; ;; ========== Git time-machine ==========
;; (use-package git-timemachine
;;   :ensure t
;;   :defer t
;;   :init
;;   (define-key global-map "\M-g" 'git-timemachine-toggle)
;;   )

;; Using org-bullets since org-superstar not working with nano
(use-package org-bullets
  :straight t)
(add-hook 'org-mode-hook (lambda () (org-bullets-mode 1)))
  
(with-eval-after-load 'org-faces
  (require 'org-indent)
  ;; set basic title font
  ;; Low levels are unimportant => no scaling
  (set-face-attribute 'org-level-7 nil :inherit 'org-level-8)
  (set-face-attribute 'org-level-6 nil :inherit 'org-level-8)
  (set-face-attribute 'org-level-5 nil :inherit 'org-level-8)
  (set-face-attribute 'org-level-4 nil :height 1.0)
  (set-face-attribute 'org-level-3 nil :height 1.0 :weight 'bold)
  (set-face-attribute 'org-level-2 nil :height 1.1)
  (set-face-attribute 'org-level-1 nil :height 1.2)
  ; (setq org-cycle-level-faces nil)
  ; (setq org-n-level-faces 4)
  ;; hide #+TITLE:
  (setq org-hidden-keywords '(title))
  (set-face-attribute 'org-document-title nil
                      :height 1.75
                      :foreground 'unspecified
                      :inherit 'org-level-1)
  ;; Ensure that anything that should be fixed-pitch in Org files appears that way
  (set-face-attribute 'org-block nil :foreground nil :inherit 'fixed-pitch)
  (set-face-attribute 'org-table nil  :inherit 'fixed-pitch)
  (set-face-attribute 'org-formula nil  :inherit 'fixed-pitch)
  (set-face-attribute 'org-code nil   :inherit '(shadow fixed-pitch))
  (set-face-attribute 'org-indent nil :inherit '(org-hide fixed-pitch))
  (set-face-attribute 'org-verbatim nil :inherit '(shadow fixed-pitch))
  (set-face-attribute 'org-special-keyword nil :inherit '(font-lock-comment-face fixed-pitch))
  (set-face-attribute 'org-meta-line nil :inherit '(font-lock-comment-face fixed-pitch))
  ;; (set-face-attribute 'org-checkbox nil :inherit 'fixed-pitch)

  ;; Get rid of the background on column views
  (set-face-attribute 'org-column nil :foreground nil :background "#0F111B" :inherit 'fixed-pitch)
  (set-face-attribute 'org-column-title nil :background nil)
  )

(add-hook 'org-mode-hook
 (lambda ()
   (variable-pitch-mode 1)
    visual-line-mode))

(setq org-agenda-custom-commands
      '(
     ("r" "Resonance Cal" tags "Type={.}" 
	   ((org-agenda-files
		 (directory-files-recursively
			"~/Documents/org/refs/rez" "\\.org$"))
	   (org-overriding-columns-format
		 "%35Item %Type %Start %Fin %Rating")
	   (org-agenda-cmp-user-defined
		 (cmp-date-property-stamp "Start"))
	   (org-agenda-sorting-strategy
		'(user-defined-down))
       (org-agenda-overriding-header "C-u r to re-run Type={.}")
       (org-agenda-mode-hook
	   (lambda ()
	     (visual-line-mode -1)
	     (setq truncate-lines 1)
	     (setq display-line-numbers-offset -1)
	     (display-line-numbers-mode 1)))
	  (org-agenda-view-columns-initially t)))
      
       ("e" "Experiments" tags "Type={.}"
	   ((org-agenda-files
		 (directory-files-recursively
			"~/Documents/org/areas/exps" "\\.org$"))
	   (org-overriding-columns-format
		 "%35Item %Start %Fin %Status %Outcome")
	   (org-agenda-cmp-user-defined
	   (cmp-date-property-stamp "Start"))
	   (org-agenda-sorting-strategy
	    '(user-defined-down))
       (org-agenda-overriding-header "C-u r to re-run Type={.}")
       (org-agenda-mode-hook
	   (lambda ()
	     (visual-line-mode -1)
	     (setq truncate-lines 1)
	     (setq display-line-numbers-offset -1)
	     (display-line-numbers-mode 1)))
	  (org-agenda-view-columns-initially t)))

       ;; org-super-agenda super view
       ("u" "Super view" 
          ((agenda "" ( (org-agenda-span 1)
		       (org-super-agenda-groups
               '(
                 (:name "Inbox"
                 :tag "inbox")
                 (:name "Today"
				 :tag ("bday" "ann" "hols" "cal" "today")
				 :time-grid t
				 :todo ("WIP")
				 :deadline today
				 :scheduled today)
                (:name "Inbox"
                 :tag "inbox")
			    (:name "Overdue"
				 :deadline past)
			    (:name "Reschedule"
				 :scheduled past)
			    (:name "Perso"
				 :tag "perso")
			    (:name "Due Soon"
				 :deadline future
				 :scheduled future)
	    		  ))))
	   (tags (concat "w" (format-time-string "%V")) ((org-agenda-overriding-header  (concat "--\nToDos Week " (format-time-string "%V")))
	   		(org-super-agenda-groups
	   		 '((:discard (:deadline t))
               (:discard (:scheduled t))
               (:discard (:todo ("DONE")))
               (:name "Ticklers"
	   			  :tag "someday")
	   		   (:name "Perso"
	   			  :and (:tag "perso" :not (:tag "someday")))
               (:name "Work"
	   		     :and (:tag "work" :not (:tag "someday")))
               (:name "Uni"
	   			  :and (:tag "uni" :not (:tag "someday")))
	   		   (:name "Ping"
	   			  :tag "crm")
	   		   ))))
	   ))))

(use-package org-super-agenda
  :straight t
  :after org
  :defer t
  :config
  (org-agenda nil "u")
  )
; ;; (org-super-agenda-mode t)

; (setq lexical-binding t)
(defun cmp-date-property-stamp (prop)
	"Compare two `org-mode' agenda entries, `A' and `B', by some date property.
If a is before b, return -1. If a is after b, return 1. If they
are equal return nil."
;; source: https://emacs.stackexchange.com/questions/26351/custom-sorting-for-agenda/26369#26369
	(lexical-let ((prop prop))
	 #'(lambda (a b)

		(let* ((a-pos (get-text-property 0 'org-marker a))
					 (b-pos (get-text-property 0 'org-marker b))
					 (a-date (or (org-entry-get a-pos prop)
											 (format "<%s>" (org-read-date t nil "now"))))
					 (b-date (or (org-entry-get b-pos prop)
											 (format "<%s>" (org-read-date t nil "now"))))
					 (cmp (compare-strings a-date nil nil b-date nil nil))
					 )
			(if (eq cmp t) nil (signum cmp))
			))))

; general is needed for origami keymaps for org-super-agenda
(use-package general
  :straight t)

(use-package origami
  :straight t
  :hook (org-agenda-mode . origami-mode)
  :general
  (:keymaps 'org-super-agenda-header-map
                     "<tab>" #'origami-toggle-node))

(use-package org-download
 		:straight t
 		:after org
 		:defer nil
 		:custom
 		(org-download-method 'directory)
 		(org-download-image-dir "~/Documents/org/refs/images")
 		(org-download-heading-lvl nil)
 		(org-download-timestamp "%Y%m%d-%H%M%S_")
 		(org-image-actual-width 800)
 		(org-download-screenshot-method "/opt/homebrew/bin/pngpaste %s")
 		:bind
 		("C-M-y" . org-download-screenshot)
 		)

  ;; Displaying week numbers in calendar
  (copy-face font-lock-constant-face 'calendar-iso-week-face)
  (set-face-attribute 'calendar-iso-week-face nil
                    :height 0.9)
  (setq calendar-intermonth-text
      '(propertize
        (format "W%2d"
                (car
                 (calendar-iso-from-absolute
                  (calendar-absolute-from-gregorian (list month day year)))))
        'font-lock-face 'calendar-iso-week-face))

;; Org Journal config
(use-package org-journal
  :straight t
  :defer t
  :custom
  (org-journal-dir "~/Documents/org/journal")
  (org-journal-file-type 'yearly)
  ; (org-extend-today-until 01)
  (org-journal-file-format "journal-%Y.org")
  (org-journal-date-format "%Y-%m-%d %a")
  (org-journal-created-property-timestamp-format "%Y-%m-%d")
  (org-journal-encrypt-journal t)
  (org-journal-enable-cache t)
  (org-journal-carryover-items nil))

;; ========== Ivy  config  ==========

(use-package ivy
  :straight t
  :config
  (ivy-mode 1)
  (setq ivy-use-virtual-buffers t)
  (setq enable-recursive-minibuffers t)
  (setq ivy-count-format "(%d/%d) ")
  (global-set-key (kbd "C-c C-r") 'ivy-resume)
  )

(use-package ivy-rich
  :after ivy
  :straight t
  :config
  (setq ivy-virtual-abbreviate 'full
	ivy-rich-switch-buffer-align-virtual-buffer t)
  (setq ivy-rich-path-style 'abbrev)
  )

(use-package swiper
  :straight t
  :config
  (global-set-key (kbd "C-f") 'swiper))

;; ========== Projectile config  ==========

; (use-package projectile
;   :straight t
;   :defer t
;   :init
;   (setq projectile-completion-system 'ivy)
;   (projectile-mode)
;   )

;; ========== Company config  ==========

; (use-package company
;   :straight t
; 	:defer t)
; (add-hook 'after-init-hook 'global-company-mode)

;; ========== Org-roam config ==========



;; (use-package emacsql-sqlite-builtin
;;  :straight t)

(load-file "~/.config/emacs/org-roam-capture-templates.el")
(use-package org-roam
  ;; :straight t (org-roam :type git :host github :repo "org-roam/org-roam")
    :straight t
	:init
    (setq org-roam-directory (file-truename "~/Documents/org/"))
    (setq org-roam-file-extensions '("org" "md"))
    (setq org-roam-dailies-directory "logs")
    (setq find-file-visit-truename t)
    (setq org-roam-mode-sections
	      (list #'org-roam-backlinks-section
		   ;; #'org-roam-reflinks-section
		   #'org-roam-unlinked-references-section
		   ))
    ;;:custom
    ;;(org-roam-database-connector 'sqlite-builtin)
     
    :bind (("C-c n l" . org-roam-buffer-toggle)
         ("C-c n f" . org-roam-node-find)
         ("C-c n i" . org-roam-node-insert))
     :config
     (org-roam-setup)
     )

(use-package md-roam
  :straight (:host github :repo "nobiot/md-roam")
  :after org-roam
  )
(md-roam-mode 1)
(setq md-roam-file-extension "md")

(org-roam-db-autosync-mode)

;; Override silly format of filenames
(cl-defmethod org-roam-node-slug ((node org-roam-node))
  "Return the slug of NODE."
  (let ((title (org-roam-node-title node))
        (slug-trim-chars '(;; Combining Diacritical Marks https://www.unicode.org/charts/PDF/U0300.pdf
                           768 ; U+0300 COMBINING GRAVE ACCENT
                           769 ; U+0301 COMBINING ACUTE ACCENT
                           770 ; U+0302 COMBINING CIRCUMFLEX ACCENT
                           771 ; U+0303 COMBINING TILDE
                           772 ; U+0304 COMBINING MACRON
                           774 ; U+0306 COMBINING BREVE
                           775 ; U+0307 COMBINING DOT ABOVE
                           776 ; U+0308 COMBINING DIAERESIS
                           777 ; U+0309 COMBINING HOOK ABOVE
                           778 ; U+030A COMBINING RING ABOVE
                           780 ; U+030C COMBINING CARON
                           795 ; U+031B COMBINING HORN
                           803 ; U+0323 COMBINING DOT BELOW
                           804 ; U+0324 COMBINING DIAERESIS BELOW
                           805 ; U+0325 COMBINING RING BELOW
                           807 ; U+0327 COMBINING CEDILLA
                           813 ; U+032D COMBINING CIRCUMFLEX ACCENT BELOW
                           814 ; U+032E COMBINING BREVE BELOW
                           816 ; U+0330 COMBINING TILDE BELOW
                           817 ; U+0331 COMBINING MACRON BELOW
                           )))
    (cl-flet* ((nonspacing-mark-p (char)
                                  (memq char slug-trim-chars))
               (strip-nonspacing-marks (s)
                                       (ucs-normalize-NFC-string
                                        (apply #'string (seq-remove #'nonspacing-mark-p
                                                                    (ucs-normalize-NFD-string s)))))
               (cl-replace (title pair)
                           (replace-regexp-in-string (car pair) (cdr pair) title)))
      (let* ((pairs `(("[^[:alnum:][:digit:]]" . "-")  ;; convert anything not alphanumeric
                      ("--*" . "-")                    ;; remove sequential underscores
                      ("^-[:digit;]-" . "")            ;; remove starting underscores
                      ("-$" . "")))                    ;; remove ending underscores
             (slug (-reduce-from #'cl-replace (strip-nonspacing-marks title) pairs)))
        (downcase slug)))))

; ;; for org-roam-buffer-toggle
; ;; Recommendation in the official manual
(add-to-list 'display-buffer-alist
               '("\\*org-roam\\*"
                  (display-buffer-in-direction)
                  (direction . right)
                  (window-width . 0.33)
                  (window-height . fit-window-to-buffer)))

;; ========== Xeft configuration ==========

(straight-use-package
 '(xeft :host nil :repo "https://git.sr.ht/~casouri/xeft"
        :files  (:defaults "*.h" "Makefile" "xapian-lite.cc")))
; (setq deft-default-extension "org")
(setq xeft-database "~/.config/emacs")
(setq xeft-directory "~/Documents/org")
(setq xeft-recursive t)

;; ========== Linting ==========

(use-package flycheck
  :straight t
  :init
  (global-flycheck-mode)
  )

(straight-use-package 'lsp-mode)
(straight-use-package 'company-mode)
(straight-use-package 'lsp-ui)

(straight-use-package 'rust-mode)
  (add-hook 'rust-mode-hook #'lsp)
  (add-hook 'rust-mode-hook
          (lambda () (setq indent-tabs-mode nil)))
  (setq rust-format-on-save t)

; ;; =========  Writegood mode ==============
; (use-package writegood-mode
; 	:straight t
; ; 	:config
; ; 	(global-set-key (kbd "C-c C-g") 'writegood-mode)
; ; 	(global-set-key (kbd "C-c C-r") 'writegood-grade-level)
; ;   (global-set-key (kbd "C-c C-e") 'writegood-reading-ease)
; )

;; ============= Org pretty table ====================
(straight-use-package
  '(org-pretty-table :type git :host github :repo "Fuco1/org-pretty-table"))
(add-hook 'org-mode-hook (lambda () (org-pretty-table-mode)))

;; ========== Place Backup Files in Specific Directory ==========

;; Enable backup files.
(setq make-backup-files t)
(setq backup-by-copying t)
;; Enable versioning with default values (keep five last versions, I think!)
(setq delete-old-versions t
  kept-new-versions 5
  kept-old-versions 2
  version-control t)
;; Save all backup file in this directory.
(setq backup-directory-alist (quote ((".*" . "~/.emacs_backups"))))
(setq undo-tree-history-directory-alist '(("." . "~/.emacs_undos")))


;; ========== Copying, killing, yanking goes to system slipboard  ==========

(defun pbcopy ()
  (interactive)
  (call-process-region (point) (mark) "pbcopy")
  (setq deactivate-mark t))

(defun pbpaste ()
  (interactive)
  (call-process-region (point) (if mark-active (mark) (point)) "pbpaste" t t))

(defun pbcut ()
  (interactive)
  (pbcopy)
  (delete-region (region-beginning) (region-end)))

(global-set-key (kbd "C-c c") 'pbcopy)
(global-set-key (kbd "C-c v") 'pbpaste)
(global-set-key (kbd "C-c x") 'pbcut)

(defun delete-file-and-buffer ()
  "Kill the current buffer and deletes the file it is visiting."
  (interactive)
  (let ((filename (buffer-file-name)))
    (when filename
      (if (vc-backend filename)
          (vc-delete-file filename)
        (progn
          (delete-file filename)
          (message "Deleted file %s" filename)
          (kill-buffer))))))

;;--------------------------
;; Handling file properties for ‘CREATED’ & ‘LAST_MODIFIED’
;;--------------------------

  (defun zp/org-find-time-file-property (property &optional anywhere)
    "Return the position of the time file PROPERTY if it exists.
When ANYWHERE is non-nil, search beyond the preamble."
    (save-excursion
      (goto-char (point-min))
      (let ((first-heading
             (save-excursion
               (re-search-forward org-outline-regexp-bol nil t))))
        (when (re-search-forward (format "^#\\+%s:" property)
                                 (if anywhere nil first-heading)
                                 t)
          (point)))))

  (defun zp/org-has-time-file-property-p (property &optional anywhere)
    "Return the position of time file PROPERTY if it is defined.
As a special case, return -1 if the time file PROPERTY exists but
is not defined."
    (when-let ((pos (zp/org-find-time-file-property property anywhere)))
      (save-excursion
        (goto-char pos)
        (if (and (looking-at-p " ")
                 (progn (forward-char)
                        (org-at-timestamp-p 'lax)))
            pos
          -1))))

  (defun zp/org-set-time-file-property (property &optional anywhere pos)
    "Set the time file PROPERTY in the preamble.
When ANYWHERE is non-nil, search beyond the preamble.
If the position of the file PROPERTY has already been computed,
it can be passed in POS."
    (when-let ((pos (or pos
                        (zp/org-find-time-file-property property))))
      (save-excursion
        (goto-char pos)
        (if (looking-at-p " ")
            (forward-char)
          (insert " "))
        (delete-region (point) (line-end-position))
        (let* ((now (format-time-string "[%Y-%m-%d %a %H:%M]")))
          (insert now)))))

  (defun zp/org-set-last-modified ()
    "Update the LAST_MODIFIED file property in the preamble."
    (when (derived-mode-p 'org-mode)
      (zp/org-set-time-file-property "MODIFIED")))

(provide 'init)
;;; init.el ends here
